package com.dbq.fast.business.me;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.coupons.CouponsActivity;
import com.dbq.fast.business.me.api.ShareApi;
import com.dbq.fast.business.me.bean.InviteFriendsInfoBean;
import com.dbq.fast.business.me.bean.InviteFriendssSubmitBean;
import com.dbq.fast.business.me.ui.ShareDialog;
import com.dbq.fast.common.base.BaseActivity;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.common.net.glide.GlideApp;
import com.dbq.fast.util.AndroidBug5497Workaround;
import com.dbq.fast.util.ProgressDialogUtil;
import com.dbq.fast.util.SystemUtil;
import com.dbq.fast.view.EditTextWithSubmit;
import com.dbq.share.BaseAssistActivity;
import com.dbq.share.ShareCallback;
import com.dbq.share.ShareUtil;
import com.dbq.share.ShareWebPage;
import com.dbq.share.SinaAssistActivity;
import com.tencent.mm.opensdk.modelbase.BaseResp;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 分享页面
 * Created by Administrator on 2017/12/28 0028.
 */

public class ShareActivity extends BaseActivity implements EditTextWithSubmit.EditTextWithSubmitAction {
    @BindView(R.id.share_btn)
    TextView share;
    @BindView(R.id.share_entry_details)
    TextView share_entry_details;
    @BindView(R.id.share_info)
    TextView share_info;
    @BindView(R.id.share_imageview)
    ImageView share_imageview;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.edit_submit)
    EditTextWithSubmit mEditTextWithSubmit;
    @BindView(R.id.share_info_tips)
    LinearLayout share_info_tips;

    Unbinder unbinder;
    InviteFriendsInfoBean mInviteFriendsInfoBean;

    private ShareDialog.Builder builder;
    private ShareDialog mDialog;
    String TAG = ShareActivity.class.getSimpleName();
    //针对微信分享
    private int stopCount = 0;// 根据stop 执行的次数来判断 在分享时用户是否选择了留在微信
    private boolean isRequestShare = false; // 用户是否发起了分享动作


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.share_activity);
        unbinder = ButterKnife.bind(this);
        mEditTextWithSubmit.setEditTextWithSubmitAction(this);
        getDataFromServer();
        AndroidBug5497Workaround.assistActivity(this);
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        decorView.setSystemUiVisibility(uiOptions);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "onStop");
        stopCount++;
        if (stopCount == 2 && isRequestShare) {
            // 此种情况为用户分享成功后 点击了留在微信按钮
            ProgressDialogUtil.hideProgress();
            BaseResp baseResp = new BaseResp() {
                @Override
                public int getType() {
                    return 2;
                }

                @Override
                public boolean checkArgs() {
                    return false;
                }
            };
            baseResp.errCode = BaseResp.ErrCode.ERR_OK;
            ShareUtil.handlerWxShareOnRespData(ShareActivity.this, baseResp);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume");
        stopCount = 0;
        isRequestShare = false;
    }

    @OnClick({R.id.share_btn, R.id.back, R.id.share_entry_details})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.share_btn:
                showShareDialog(view);
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.CLICK_SHARE_MY_CODE);
                break;
            case R.id.back:
                finish();
                break;
            case R.id.share_entry_details:
                //跳转卡券已使用
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.CLICK_MY_SHARE);
                Intent intent = new Intent(ShareActivity.this, CouponsActivity.class);
                intent.putExtra("page", "1");
                startActivity(intent);
                break;
        }
    }

    private void showShareDialog(View view) {
        if (mInviteFriendsInfoBean != null) {
            ShareUtil.instance().showShareDialog(view, this, new ShareWebPage(mInviteFriendsInfoBean.getTitle(),
                            mInviteFriendsInfoBean.getSubhead(), mInviteFriendsInfoBean.getInviteShareUrl(),
                            BitmapFactory.decodeResource(App.getContext().getResources(), R.mipmap.app_icon)),
                    new ShareCallback() {
                        @Override
                        public void showSelectorDialog() {
                            Log.e("SK", "显示选择弹窗");
                        }

                        @Override
                        public void startShare(String media) {
                            isRequestShare = true;
                            Log.e("SK", "点击：" + media + ",开始分享");
                        }

                        @Override
                        public void shareFail(String media, int errCode, String errMsg) {
                            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.SHARE_CANCEL);
                            isRequestShare = false;
                            Log.e("SK", "分享失败：" + media + ",errCode:" + errCode + ",errMsg:" + errMsg);
                        }

                        @Override
                        public void shareComplete(String media) {
                            Log.e("SK", media + ",分享成功");
                            isRequestShare = false;
                        }

                        @Override
                        public void showProgress(BaseAssistActivity activity) {
                            if (activity.isResume()) {
                                if (activity instanceof SinaAssistActivity) {
                                } else {
                                    ProgressDialogUtil.showProgress(activity, "", "");
                                }
                            }
                        }

                        @Override
                        public void hideProgress() {
                            ProgressDialogUtil.hideProgress();
                        }
                    });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    /**
     * 从网络获取数据
     **/
    public void getDataFromServer() {
        ShareApi.questService(new RemoteApiCallBack<InviteFriendsInfoBean>() {
            @Override
            public void onFail(int status, String message) {
                Toast.makeText(ShareActivity.this, message, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onSuccess(InviteFriendsInfoBean o) {
                mInviteFriendsInfoBean = o;
                updateView(o);
            }
        });
    }

    /**
     * 刷新UI
     **/
    private void updateView(InviteFriendsInfoBean o) {
        if (o != null) {
            try {
                GlideApp.with(this)
                        .load(o.getMapUrl())
                        .into(share_imageview); //图片加载
            } catch (Exception e) {
                Log.e(TAG, "图片加载失败");
            }
            share_info.setText(o.getRule()); //邀请规则
            updateTextTips(o.getInviteCounts());//更新优惠券
            share.setText("分享我的邀请码" + o.getVpnId());//分享邀请码
            //设置是否可以邀请我Ui
            if (o.getIsInviteeStatus() == 0) {
                mEditTextWithSubmit.setVisibility(View.VISIBLE);
                share_info_tips.setVisibility(View.GONE);
            } else {
                mEditTextWithSubmit.setVisibility(View.GONE);
                share_info_tips.setVisibility(View.VISIBLE);
            }
        }
    }

    private void updateTextTips(int inviteCount) {
        String str = "你已获得" + inviteCount + "天套餐延长，查看奖励详情>";
        SpannableStringBuilder style = new SpannableStringBuilder(str);
        //style.setSpan(new ForegroundColorSpan(Color.BLUE), 4, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new ForegroundColorSpan(Color.parseColor("#0082E3")), str.length() - 5, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        share_entry_details.setText(style);
    }

    /***
     * 发送网络请求，提交邀请码
     * @param shareCode
     */
    @Override
    public void submit(String shareCode) {
        YibaAnalysis.getInstance().event(App.getContext(), EventConstant.SUBMIT_CODE);
        if (!TextUtils.isEmpty(shareCode)) {
            if (isResume) {
                ProgressDialogUtil.showProgress(ShareActivity.this, "", getResources().getString(R.string.waiting));
            }
            ShareApi.submitShareCode(new RemoteApiCallBack<InviteFriendssSubmitBean>() {
                @Override
                public void onFail(int status, String message) {
                    if (isResume) {
                        ProgressDialogUtil.hideProgress();
                    }
                    Toast.makeText(ShareActivity.this, status == 404 ? "Network exception, please try again later" : message, Toast.LENGTH_LONG).show();
                }

                @Override
                public void onSuccess(InviteFriendssSubmitBean amount) {
                    showSuccessDialog(amount.getAmount());
                    if (isResume) {
                        ProgressDialogUtil.hideProgress();
                    }
                }
            }, shareCode);
        } else {
            Toast.makeText(ShareActivity.this, "Please input invited code", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 弹出对话框，更新用户信息
     **/
    private void showSuccessDialog(int amount) {
        builder = new ShareDialog.Builder(this);
        mDialog = builder.setMessage(amount + "")
                .setSingleButton("好的", v -> {
                    mDialog.dismiss();
                    mEditTextWithSubmit.setVisibility(View.GONE);
                    share_info_tips.setVisibility(View.VISIBLE);
                    //刷新UI
                    getDataFromServer();
                }).createSingleButtonDialog();
        mDialog.show();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                SystemUtil.hideKeyboard(v.getWindowToken(), ShareActivity.this);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * android 点击外部区域 关闭软键盘
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};

            v.getLocationInWindow(l);

            int left = l[0];
            int top = l[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();

            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }
}
